package com.fingard.dsp.bank.directbank.hbc02;

import com.fingard.dsp.bank.directbank.bankInterface.IFileResolveDifference;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class HBC02ForeignBank extends HBC02Base implements IFileResolveDifference {
    /**
     * MT942获取余额差异处理方法
     * @param context
     * @param accountNum
     * @param date
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, String> getBalanceMap(String context, String accountNum, String date) throws Exception {
        String closeBal="";
        String availBal="";
        String openBal="";
        String lastBal="";
        String[] contentArr=context.split(tag61);
        String contentOne=contentArr[0];//第一条明细
        String contentLast=contentArr[contentArr.length-1];//最后一条明细
        //获取第一条明细的余额和交易额，计算期初余额
        if(StringHelper.hasAnyChar(contentOne)){
            String[] detailsplit = contentOne.split(tag86);
            //解析61
            int index2=0;
            String cdFlag="";
            if(isLetter(detailsplit[0].substring(6, 7).charAt(0))){
                //借贷标识 D C RC RD EC ED
                cdFlag = detailsplit[0].charAt(6) + "";
                index2 = 6;
                if ("R".equals(cdFlag) || "E".equals(cdFlag)) {
                    cdFlag = detailsplit[0].substring(6, 8);
                    index2=7;
                }
            }else {
                //借贷标识 D C RC RD
                cdFlag = detailsplit[0].charAt(10) + "";
                index2 = 10;
                if ("R".equals(cdFlag) || "E".equals(cdFlag)){
                    cdFlag = detailsplit[0].substring(10, 12);
                    index2=11;
                }
            }
            //判断借贷表示
            if("RD".equals(cdFlag)){
                cdFlag="C";
            }else if("RC".equals(cdFlag)){
                cdFlag="D";
            }
            if(cdFlag.contains("E")){
                cdFlag=cdFlag.substring(1);//借贷标识
            }
            if(isLetter(detailsplit[0].substring(index2+1).charAt(0))){
                index2=index2+1;
            }
            //交易金额
            //校验61节点金额是否返回小数点
            int index = detailsplit[0].indexOf(",", index2) + 1;
            int count=1;//记录返回几位小数,最多判断三位
            for(int i=0;i<3;i++){
                if(!isLetter(detailsplit[0].substring(index+i, index + 1 + i).charAt(0))){
                    count++;
                }else {
                    break;
                }
            }
            //说明没有返回小数点
            index=detailsplit[0].indexOf(",", index2) + count;
            /*if(isLetter(detailsplit[0].substring(index, index+1).charAt(0))){
                //说明没有返回小数点
                index = detailsplit[0].indexOf(",", index2) + 1;
            }else {
                //说明返回小数点
                index = detailsplit[0].indexOf(",", index2) + 3;
            }*/
            String transAmt = detailsplit[0].substring(index2 + 1, index).replace(",", ".");
            transAmt = amtCheck(transAmt);//交易额
            //解析86
            String[] contentOne86 = detailsplit[1].split("\r\n");
            //提取余额：干掉,号，转成double不报错则为余额
            String balance="";
            for(String content:contentOne86){
                try{
                    balance=Double.parseDouble(content.replaceAll(",",""))+"";
                }catch (Exception e){
                    continue;
                }
                if(StringHelper.hasAnyChar(balance)){
                    continue;
                }
            }
            if("D".equals(cdFlag)){
                lastBal=new BigDecimal(balance).add(new BigDecimal(transAmt))+"";
            }else {
                lastBal=new BigDecimal(balance).subtract(new BigDecimal(transAmt))+"";
            }
        }
        //获取最后一条 明细的余额，计算期末余额和期末当前余额
        if(StringHelper.hasAnyChar(contentLast)) {
            String[] detailsplit = contentLast.split(tag86);
            //解析86
            String[] contentOne86 = detailsplit[1].split("\r\n");
            //提取余额：干掉,号，转成double不报错则为余额
            String balance="";
            for(String content:contentOne86){
                try{
                    balance=Double.parseDouble(content.replaceAll(",",""))+"";
                }catch (Exception e){
                    continue;
                }
                if(StringHelper.hasAnyChar(balance)){
                    continue;
                }
            }
            closeBal=new BigDecimal(balance)+"";
            availBal=closeBal;

        }
        //返回
        Map<String,String> map=new HashMap<String, String>();
        map.put("closeBal",closeBal);
        map.put("availBal",availBal);
        map.put("openBal","0");
        map.put("lastBal",lastBal);
        return map;
    }

    /**
     * MT942的86字段获取对方信息数据差异处理方法
     * @param string86
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, String> getRecInformationMap(String string86) throws Exception {
        //定义元素
        String reqId="";//交易流水号
        String recAct = "";//对方账户
        String recName = "";//对方名称
        String recBankName="";//对方银行名称
        String recDetail = "";//备注
        String cdFlag=string86.substring(0,string86.indexOf("#@#"));
        String[] detailsplit = string86.substring(string86.indexOf("#@#")+3).split("\r\n");
        if(detailsplit.length>0 && !"TOTAL CHARGE:".equals(detailsplit[0])){
            reqId=detailsplit[0];
        }
        if(detailsplit.length>1 && "TOTAL CHARGE:".equals(detailsplit[0])){
            reqId=detailsplit[1];
        }else {
            recName=detailsplit[1];
        }
        if(detailsplit.length>2 && StringHelper.hasAnyChar(detailsplit[2])){
            if("D".equals(cdFlag)){
                if(detailsplit[2].getBytes().length>35 || "TOTAL CHARGE:".equals(detailsplit[0])){//支持35个英文字母
                    recName=detailsplit[2];//长于11个中文字符或者为手续费流水，此处为对方名称
                }else {
                    recDetail=detailsplit[2];//否则为附言
                }
            }else {
                if(detailsplit[2].getBytes().length>35){//支持35个英文字母
                    recName=detailsplit[2];
                }
            }
        }
        if(detailsplit.length>3 && StringHelper.hasAnyChar(detailsplit[3])){
            recDetail=recDetail+detailsplit[3];
        }
        if(detailsplit.length>4 && StringHelper.hasAnyChar(detailsplit[4])){
            recBankName=detailsplit[4];
        }
        //返回值
        Map<String,String> map=new HashMap<String, String>();
        map.put("reqId",reqId);
        map.put("recAct",recAct);
        map.put("recName",recName);
        map.put("recBankName",recBankName);
        map.put("recDetail",recDetail);
        return map;
    }

    @Override
    public void analysisAckFile(String filePath) throws Exception {
        String ackFilePath=StringHelper.trimEndFileSp(getBankConfig().getValueAsString("DealedPath"));
        String[] rspStatus=new String[]{"","",""};
        //判断文件存不存在，不存在就不处理
        String context2 = FileHelper.readFileText(filePath, getCharset());
        if (StringHelper.isNullOrEmpty(context2)) {
            WriteBankLogLn("文件解析失败：-------" + filePath);
            throw new Exception("读取文件内容异常：" + filePath);
        }
        WriteBankLogLn2("读取文件:" + filePath + "中的内容：\r\n" + context2);
        String context3=context2.replaceAll("\r","").replaceAll("\n","").replaceAll("\t","");
        String[] contentAry=context3.split(",");
        for(int i=0;i<contentAry.length;i++){
            contentAry[i]=contentAry[i].trim();
        }
        if(contentAry.length>12 && contentAry[3].length()==10){
            String payDate=DateHelper.convertD10toD8(contentAry[3]);//支付日期
            if("1".equals(contentAry[0])){
                String[] context4=context2.replaceAll("\r","").split("\n");
                if(context4.length>1){
                    //取第二行数据进行处理
                    String qryStatus=context4[1];
                    String[] contentAry2=qryStatus.split(",");
                    for(int i=0;i<contentAry2.length;i++){
                        contentAry2[i]=contentAry2[i].trim();
                    }
                    rspStatus[0]=contentAry2[contentAry2.length-7];//付款流水号
                    rspStatus[1]="1+"+contentAry2[contentAry2.length-2];//状态码
                    rspStatus[2]=contentAry2[contentAry2.length-2]+":"+contentAry2[contentAry2.length-1];
                    //生成ack处理文件
                    getAckStatus(ackFilePath,payDate,rspStatus,"2");
                    WriteBankLogLn("ack-Lv.2文件已处理");
                }
            }else if("2".equals(contentAry[0]) && contentAry[contentAry.length-2].length()==2){
                rspStatus[0]=contentAry[contentAry.length-8];//付款流水号
                rspStatus[1]="2+"+contentAry[contentAry.length-2];//状态码
                rspStatus[2]=contentAry[contentAry.length-2]+":"+contentAry[contentAry.length-1];
                //生成ack处理文件
                getAckStatus(ackFilePath,payDate,rspStatus,"1");
                WriteBankLogLn("ack-Lv.1文件已处理");
            }else {
                WriteBankLogLn("文件数据不符合规则："+context2);
            }
        }else {
            WriteBankLogLn("文件数据不符合规则："+context2);
        }
    }
}
